package Handlers;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Annotations.EntryPoint;
import Commands.ClientCommandContext;
import Commands.ClientCommandResult;
import Commands.ClientCommands;
import Helpers.ApplicationInitialiser;
import Helpers.ApplicationLogger;

@EntryPoint
public class CommonHandler extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {   
		processRequest(req, resp);
    }
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		    processRequest(req, resp);
	}
	
	private void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String commandName = req.getParameter("commandName");
        String command = req.getParameter("command");
         
        if(commandName == null || command == null || commandName.length() == 0 || command.length() == 0)
        {
        	resp.sendRedirect("default.jsp");
        	return;
        }
        
        ApplicationInitialiser.getInstance().Initialize();
        ApplicationLogger.getInstance().LOG.info("Forming Context...");
        ClientCommandContext context = new ClientCommandContext();
        ApplicationLogger.getInstance().LOG.info("HostIP is " + req.getRemoteHost());
        context.put("HostIP", req.getRemoteHost());
        ApplicationLogger.getInstance().LOG.info("CommandName: " + commandName + " Command: " + command);
        ClientCommandResult commandExecutionResult = new ClientCommandResult();
        commandExecutionResult = ClientCommands.getInstance().ExecuteCommand(commandName, command, context);
        resp.setContentType(commandExecutionResult.getContentType());
		
	    PrintWriter pw = resp.getWriter();
	    ApplicationLogger.getInstance().LOG.info("SerializedResult: " + commandExecutionResult.getSerializedResult());
	    pw.println(commandExecutionResult.getSerializedResult());
	}
}
